'use strict';
var encoding = require('encoding');

let http = require("http");  
let key = '8292b4d51f3900b8f44d8810c7231c3c';
// let place = encoding.convert("北京", "utf8");
let urllocal = 'http://api.openweathermap.org/data/2.5/weather';

//暴漏定义的模块方法
exports.getUrl = getUrl;
function getUrl(place) {
  let urlw = urllocal+'?q='+'\''+place+'\''+'&appid='+key;
  console.log('-----urlw-------',urlw);
  return urlw;
} 

var orientdb = require('node-orientdb-http');

/*
	将中文转为拼音
*/
var transliteration = require('transliteration');	
function getPinYin(value){
	var rvalue=transliteration.transliterate(value);
	return rvalue;
}

exports.getWeather = getWeather;
function getWeather(citylist) {
	let obj1 = {};
	//console.log('this.getUrl()---------',citylist);
	var len = citylist.length;
	for(var i=0;i<len;i++){
		var place = citylist[i].pinYin;
		var url = getUrl(place);
		let req = http.get(url, function(res) {
			let data = '';
			res.on('data', function(d) {
			  data += d;
			  var aa = process.stdout.write(d);
			});
			res.on('end',function(){
			
				//把数据保存到数据库
				var obj1 = JSON.parse(data);
				var weather = createWeatherObject(obj1);
				console.log('----------weather---------------',weather);
				saveWeather(weather,1);
				//console.log('----------weather---------------',weather);
			});
			res.on('error', function(e) {
			  console.error(e);
		    });
		});
	}
}


/*
	连接数据库，并插表中
*/
function saveWeather(weather,flag){

	var db = orientdb.connect({
	    host: "http://localhost:2480",
	    user: "root",
	    password: "admin",
	    database: "weather"
	});
	//flag=0;
	var nowTime = getCurrentTime() ;
	db.on('connect', function() {
		console.log('----------数据库连接成功了--------');
		var info = 'cityName='+'"'+weather.cityName+'"'+
		',humidity='+'"'+weather.humidity+'"'+
		',sunrise='+'"'+weather.sunrise+'"'+
		',pressure='+'"'+weather.pressure+'"'+
		',clouds='+'"'+weather.clouds+'"'+
		',temp='+'"'+weather.temp+'"'+
		',temp_min='+'"'+weather.temp_min+'"'+
		',temp_max='+'"'+weather.temp_max+'"'+
		',icon='+'"'+weather.icon+'"'+
		',description='+'"'+weather.description+'"'+
		',weatherMain='+'"'+weather.weatherMain+'"'+
		',visibility='+'"'+weather.visibility+'"'+
		',editTime='+'"'+nowTime+'"'+
		',weatherId='+'"'+weather.weatherId+'"';
		if(flag==0){
			var sql = 'insert into TODAYWEATHER set '+info;
			console.log('----------sql--------',sql);
		    db.command(sql).then(function(){
		    	console.log('----------数据库插入成功了--------');
		    }, function(){
				console.log('----------数据库插入失败了--------');
			});
		}
		else{
			var sql = 'update TODAYWEATHER set '+info+'';
			console.log('----------sql--------',sql);
		    db.command(sql).then(function(){
			    console.log('----------数据库更新成功了--------');
			    }, function(){
				console.log('----------数据库更新失败了--------');
			});
		}

	});
	db.on('error', function(err) {
	    console.log('----------数据库连接失败了--------');
	});
}

exports.getCityAll = getCityAll;
function  getCityAll(){
	var wf = require('../util/weather');
	var citylist = [];
	var db = orientdb.connect({
	    host: "http://localhost:2480",
	    user: "root",
	    password: "admin",
	    database: "weather"
	});
	db.on('connect', function() {
		var sql = 'select * from CITY';
		console.log('----------sql--------',sql);
		db.query(sql).then(function(data){
		    console.log('----------查询城市列表成功了--------');
		    citylist = data.result;	
		    wf.getFWeather(citylist,1);	    
		    getWeather(citylist,1);
		  
		    //console.log('----------查询城市列表成功了--------',citylist);
		}, function(){
    		console.log('----------查询城市列表失败了--------');
		});
	});
	db.on('error', function(err) {
	    console.log('----------数据库连接失败了--------');
	});
}

exports.getCityAll1 = getCityAll1;
function  getCityAll1(ww){
	var wf = require('../util/weather');
	var citylist = [];
	var db = orientdb.connect({
	    host: "http://localhost:2480",
	    user: "root",
	    password: "admin",
	    database: "weather"
	});
	db.on('connect', function() {
		var sql = 'select * from CITY';
		console.log('----------sql--------',sql);
		db.query(sql).then(function(data){
		    console.log('----------查询城市列表成功了--------');
		    citylist = data.result;	
		    ww.success(citylist);
		    //console.log('----------查询城市列表成功了--------',citylist);
		}, function(){
    		console.log('----------查询城市列表失败了--------');
		});
	});
	db.on('error', function(err) {
	    console.log('----------数据库连接失败了--------');
	});
}

//查询所有的以获取天气的城市
function getWeatherCityAll(){
	var weatherlist = [];
	var db = orientdb.connect({
	    host: "http://localhost:2480",
	    user: "root",
	    password: "admin",
	    database: "weather"
	});
	db.on('connect', function() {
		var sql = 'select * from TODAYWEATHER';
		console.log('----------sql--------',sql);
		db.query(sql).then(function(data){
		    console.log('----------已获取的天气信息列表成功了--------');
		    weatherlist = data.result;
		}, function(){
    		console.log('----------已获取的天气信息列表失败了--------');
		});
	});
	db.on('error', function(err) {
	    console.log('----------数据库连接失败了--------');
	});
}

exports.addCity = addCity;
function addCity(name,time,pinyin){
	console.log('----------添加城市部分--------',getPinYin(name));
	var we = require('../util/weather');
	var db = orientdb.connect({
	    host: "http://localhost:2480",
	    user: "root",
	    password: "admin",
	    database: "weather"
	});
	db.on('connect', function() {
		var info = 'name='+'"'+name+'"'+
		',createTime='+'"'+time+'"'+
		',editTime='+'"'+time+'"'+
		',pinYin='+'"'+pinyin+'"';
		var sql = 'insert into CITY set '+info;
	    db.command(sql).then(function(data){
	    	let req = http.get(getUrl(getPinYin(name)), function(res) {
				let data = '';
				res.on('data', function(d) {
				  data += d;
				  var aa = process.stdout.write(d);
				});
				res.on('end',function(){
				
					//把数据保存到数据库
					var obj1 = JSON.parse(data);
					var weather = createWeatherObject(obj1);
					console.log('----------weather---------------',weather);
					//添加当日天气
					saveWeather(weather,0);
					//添加该城市未来3到5天的天气
					var na = [];
					var firs = {};
					firs.pinYin = getPinYin(name);
					na.push(firs);
					we.getFWeather(na,0);
					//console.log('----------weather---------------',weather);
				});
				res.on('error', function(e) {
				  console.error(e);
			    });
			});

		    console.log('----------添加城市列表成功了--------',data);

		}, function(){
    		console.log('----------添加城市列表失败了--------');
		});
	});
	db.on('error', function(err) {
	    console.log('----------数据库连接失败了--------');
	});
}

function createWeatherObject(obj){
	var wea = {};
	wea.cityName=obj.name;//城市名称
	wea.humidity = obj.main.humidity;//湿度
	wea.sunrise = obj.sys.sunrise;//日升
	wea.pressure = obj.main.pressure;//大气压
	wea.clouds = obj.clouds.all;//云
	wea.temp = obj.main.temp;
	wea.temp_min = obj.main.temp_min;//最小温度
	wea.temp_max = obj.main.temp_max;//最小温度
	wea.icon = obj.weather[0].icon;
	wea.description = obj.weather[0].description;
	wea.weatherMain = obj.weather[0].main;
	wea.visibility = obj.visibility;
	wea.weatherId = obj.weather[0].id;
	return wea;
}

// 获取当前时间，格式为：2013-10-09
exports.getCurrentTime = getCurrentTime;
function getCurrentTime() {
    var Nowdate = new Date();
    var day = (Nowdate.getDate() + "");
    day = day.length == 1 ? ("0" + day) : day;
    var month = ((Nowdate.getMonth() + 1) + "");
    month = month.length == 1 ? ("0" + month) : month;
    var hour = Nowdate.getHours()+"";
    hour = hour.length==1 ? ("0" + hour) : hour;
    var minute = Nowdate.getMinutes()+"";
    minute = minute.length==1 ? ("0" + minute) : minute;
    //t = [Nowdate.getFullYear(), month, day];
    var dat = Nowdate.getFullYear()+'-'+month+'-'+day+' '+hour+':'+minute;
    return dat;
}

